package com.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.demo.dto.Result;
import com.demo.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.demo.utils.SystemConstants.DOMAIN_PREV;

@Service
public class UploadServiceImpl implements UploadService {

    @Override
    public Result<String> uploadImage(MultipartFile file, String fileDirName) {
        try {
            String fileDir = StrUtil.subBefore(fileDirName, "/", true) + "/";
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file.transferTo(new File(fileDirName));
            // String retFileDir = fileDirName.substring(fileDirName.indexOf("static/") + "static/".length());
            return Result.ok(DOMAIN_PREV + fileDirName, "文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("文件上传失败");
    }
}
